#ifndef SERIALPORTLOGGER_H
#define SERIALPORTLOGGER_H

#include <QCoreApplication>
#include <QDir>
#include <QMutex>
#include <QObject>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QTimer>

#include "BoardLogger.h"

class SerialPortLogger : public QObject
{
    Q_OBJECT

public:
    static SerialPortLogger& instance();

    // 初始化串口
    bool initialize();

    // 开始/停止监听
    void startLogging();
    void stopLogging();

    // 发送数据
    void sendData(const QByteArray& data);

    // 获取状态
    bool isConnected() const;
    QString getPortName() const;

private slots:
    void onReadyRead();
    void onErrorOccurred(QSerialPort::SerialPortError error);
    void checkConnection();

private:
    SerialPortLogger(QObject* parent = nullptr);
    ~SerialPortLogger();
    SerialPortLogger(const SerialPortLogger&) = delete;
    SerialPortLogger& operator=(const SerialPortLogger&) = delete;

    void loadConfiguration();
    bool openSerialPort();
    void closeSerialPort();

private:
    static SerialPortLogger* m_instance;
    QSerialPort* m_serialPort;
    QTimer* m_connectionTimer;
    QMutex m_mutex;

    // 配置参数
    QString m_portName;
    int m_baudRate;
    QSerialPort::DataBits m_dataBits;
    QSerialPort::Parity m_parity;
    QSerialPort::StopBits m_stopBits;
    QSerialPort::FlowControl m_flowControl;
    bool m_autoReconnect;
    int m_reconnectInterval;

    // 数据缓冲区，用于按行读取
    QByteArray m_readBuffer;
};

#endif  // SERIALPORTLOGGER_H